package com.hexu.event.service;

import com.hexu.event.dao.AdministratorDao;
import com.hexu.event.dao.UserDao;
import com.hexu.event.entity.Administrator;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

import static com.hexu.event.util.WebUtil.show;

public class AdministratorService {
    AdministratorDao administratorDao = new AdministratorDao();
    UserDao userDao = new UserDao();

    //修改管理员密码
    public boolean updateAdministrator(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //调用请求对象读取请求头参数信息
        String password= request.getParameter("password");
        //调用请求对象，向tomcat索要当前用户在服务端私人储物柜
        HttpSession session = request.getSession();
        Administrator administrator = (Administrator) session.getAttribute("administrator");
        administrator.setPassword(password);
        //判断长度
        if( password.length() < 6){
            return false;
        }

        //改变session中的值
        session.setAttribute("administrator",administrator);
        boolean flag = administratorDao.updateAdministrator(administrator);
        show(flag, request, response,"修改成功","修改失败","/hexu/administratorUpdate.html","/hexu/administratorUpdate.html");
        return flag;
    }

    //增加管理员
    public boolean addAdministrator(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //调用请求对象读取请求头参数信息
        String account= request.getParameter("account");
        String password= request.getParameter("password");
        System.out.println("新加管理员的账号："+account);
        //new一个对象传入数据
        Administrator administrator = new Administrator(null,account,password);
        //判断长度
        if(account.length() < 6 || password.length() <6){
            return false;
        }
        //判断账号是否重复
        if(!userDao.existAccount(account)){
            request.setAttribute("error","账号已存在");
            request.setAttribute("address","/hexu/administratorAdd.html");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return false;
        }
        //增加管理员
        boolean flag = administratorDao.addAdministrator(administrator);
        show(flag, request, response,"添加成功","添加失败","/hexu/administratorAdd.html","/hexu/administratorAdd.html");

        return flag;

    }
}
